package com.vsd.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.demo.annotation.LoginFilter;
import com.demo.bean.DataTable;
import com.demo.bean.Ret;
import com.demo.controller.CoreAdminController;
import com.demo.dialet.PaginationSupport;
import com.demo.util.JSONUtils;
import com.demo.util.StringUtil;
import com.demo.validator.AdminLoginValidate;
import com.mdx.mobile.commons.verfy.Md5;
import com.vsd.daoEx.model.AreaAgentEx;
import com.vsd.domain.AreaAgent;
import com.vsd.service.AreaAgentService;

@Controller
@RequestMapping("areaAgent")
@LoginFilter(validateClz=AdminLoginValidate.class)
public class AreaAgentController extends CoreAdminController{
	@Autowired
	private AreaAgentService areaAgentService;
	
	@RequestMapping("/list")
	@ResponseBody
	public String citylist(HttpSession session,@RequestParam("draw") Integer draw
			,@RequestParam("start") Integer start,@RequestParam("length") Integer length
			,@RequestParam("search[value]") String search,String areaCode,HttpServletRequest request){
		
		PaginationSupport.byPage(start/length+1, length);
		
		List<AreaAgentEx> list = areaAgentService.selectExList();
		
		return JSONUtils.serialize(new DataTable(draw+1,PaginationSupport.getContext().getTotalCount(), list));
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public String save(AreaAgent record) throws Exception{
		if(StringUtils.isBlank(record.getId())){
			
			record.setCreateTime(new Date());
			record.setRoleCode("AGENT");
			record.setPassword(Md5.md5(record.getPassword()));
			record.setState(1);
			record.setId(StringUtil.getUUID());
			areaAgentService.save(record);
		}else{
			if(StringUtils.isNotBlank(record.getPassword())) record.setPassword(Md5.md5(record.getPassword()));
			areaAgentService.updateByPrimaryKeySelective(record);
		}
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/findById")
	@ResponseBody
	public String findById(String id){
		AreaAgent r = areaAgentService.findOne(id);
		return JSONUtils.serialize(r);
	}

	@RequestMapping("/unique")
	@ResponseBody
	public String unique(String account){
		JSONObject ret = new JSONObject();
		AreaAgent c =  areaAgentService.findByAccount(account);
		if(c==null)  ret.put("valid", true);
		else ret.put("valid", false);
		return ret.toString();
	}
	
}
